package com.team7.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.team7.common.entity.Video;

import com.team7.dao.VideoDao;
import com.team7.service.VideoService;
import com.team7.vo.CommonResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class VideoServiceImpl extends ServiceImpl<VideoDao, Video> implements VideoService {
    @Resource
    private VideoDao videoDao;

    @Override
    //查询所有的视频信息，，根据课程id
    public CommonResult findAllVideo(String chapterId) {
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",chapterId);
        List<Video> videos = videoDao.selectList(wrapper);
        System.out.println(videos);
        return new CommonResult(2000,"查询成功",videos);
    }

    @Override
    public CommonResult insertVideo(Video video) {
        System.out.println(video);
        video.setGmtCreate(LocalDateTime.now().toString());
        video.setGmtModified(LocalDateTime.now().toString());

        int i = videoDao.insert(video);

        CommonResult commonResult =null;

        if (i>0){
            commonResult = new CommonResult(2000,"新增成功",null);
        }else {
            commonResult = new CommonResult( 5000,"新增失败",null);
        }
        return commonResult;
    }

    @Override
    public CommonResult updateVideo(Video video) {
        if (StringUtils.isEmpty(video.getVideoOriginalName()))
            video.setVideoOriginalName(null);
        if (StringUtils.isEmpty(video.getVideoSourceId()))
            video.setVideoSourceId(null);
        int i = videoDao.updateById(video);
        CommonResult commonResult =null;

        if (i>0){
            commonResult = new CommonResult(2000,"修改成功",null);
        }else {
            commonResult = new CommonResult( 5000,"修改失败",null);
        }
        return commonResult;
    }

    @Override
    public CommonResult deleteById(String id,Integer sort,String chapterId) {
        int i = videoDao.deleteById(id);//根据id删除对应的课时信息

        //根据课程章节id查询所有的课时信息
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",chapterId);
        //如果有排序比他大的，，将sort减一
        List<Video> videos = videoDao.selectList(wrapper);
        for (Video video : videos) {
            if (video.getSort()>sort){
                video.setSort(video.getSort()-1);
                int update = videoDao.updateById(video);
            }
        }

        CommonResult commonResult =null;

        if (i>0){
            commonResult = new CommonResult(2000,"删除成功",null);
        }else {
            commonResult = new CommonResult( 5000,"删除失败",null);
        }
        return commonResult;
    }
}